<?php
session_start();
?>
<html>
    <head>
        <link href="style3.css" rel="stylesheet" type="text/css" />
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
        <script>
            // Declaring valid date character, minimum year and maximum year
            var dtCh= "/";
            var minYear=1900;
            var maxYear=2100;
            // checking if user input is an integer
            function isInteger(s){
                var i;
                for (i = 0; i < s.length; i++){
                    // Check that current character is number.
                    var c = s.charAt(i);
                    if (((c < "0") || (c > "9"))) return false;
                }
                // All characters are numbers.
                return true;
            }

            function stripCharsInBag(s, bag){
                // passing through all characters in (s) checking if they are lessa than zero
                var i;
                var returnString = "";
                // Search through string's characters one by one.
                for (i = 0; i < s.length; i++){
                    var c = s.charAt(i);
                    if (bag.indexOf(c) == -1) returnString += c;
                }
                return returnString;
            }
            //creating days array for each month depending on no of days per each month
            // looping over the input to give the right number of days per each month
            //(4,6,9,11) = 30 days, (2) = 29 days else no of days = 31
            function DaysArray(n) {
                for (var i = 1; i <= n; i++) {
                    this[i] = 31
                    if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
                    if (i==2) {this[i] = 29}
                }
                return this
            }
            //check the poition of "/", length of day, month, year input
            function isDate(dtStr){
                var daysInMonth = DaysArray(12) // calling function DaysArray for month 12
                var pos1=dtStr.indexOf(dtCh) // checking position of /
                var pos2=dtStr.indexOf(dtCh,pos1+1) // checking position of second /
                var strMonth=dtStr.substring(0,pos1) // the month should be from the start of string till the first /
                var strDay=dtStr.substring(pos1+1,pos2) // day should be after the first / till second /
                var strYear=dtStr.substring(pos2+1) // year after the second / till end of string
                strYr=strYear
                if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
                if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
                // checking the length of each string
                for (var i = 1; i <= 3; i++) { // looping over the input year should be of 4 digits
                    if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
                }
                //parsing each string to int
                month=parseInt(strMonth)
                day=parseInt(strDay)
                year=parseInt(strYr)
                if (pos1==-1 || pos2==-1){ // checking positions of /
                    ChangeText("The date format should be : mm-dd-yyyy")
                    return false
                }
                //checking number of characters per month input and should be between 1 & 12
                if (strMonth.length<1 || month<1 || month>12){
                    ChangeText("Please enter a valid month")
                    return false
                }
                //checking number of characters per day input and should be between 1 & 31
                if (strDay.length<1 || day<1 || day>31 || day > daysInMonth[month]){
                    ChangeText("Please enter a valid day")
                    return false
                }
                //checking number of characters per year input and should be between max and min year
                if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
                    ChangeText("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
                    return false
                }
                //checking position of the (/)
                if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
                    ChangeText("Please enter a valid date")
                    return false
                }
                return true
            }
            // calling previus functions on user input
            function ValidateForm(){ // calling function isDate on the "form" to return true or false
                var dt=document.form.txtDate
                if (isDate(dt.value)==false){
                    dt.focus()
                    return false
                }
                return true
            }
            //change the taxt in the label to view errors or success massages
            function ChangeTextlabel1(text) {
                document.getElementById("label1").innerHTML= text;
            }
            function ChangeTextlabel2(text) {
                document.getElementById("label2").innerHTML= text;
            }
        </script>
         <script type="text/javascript" src="calendar.js"></script>
        <script type="text/javascript">
            function init() {
                calendar.set("dd");
            }
        </script>
    </head>
    <body>
        <form action="" method="post" onSubmit="return ValidateForm()">
            <?php
            include 'functions.php';
            $confID = intval($_GET['conference_id']);
            $crID = $_SESSION['member_id'];
            $con = mysql_connect("localhost", "root", "");

            if (!$con) {

                ('Could not connect:' . mysql_error());
            }
            mysql_select_db("mydb", $con);

            //connects to the server and selects the database
            //Query selects the short name from the conferences table with the same conference id that was sent from
            //previous page
            $confName = get_conference_name($confID);
            print "<h1>{$confName}</h1>";

            //creates a form to create a new session and assign papers to it
            // the user enters the date in three textboxes, one for the day, one for the month, and one for the year.
            echo'<h2> Set up a Conference Session</h2>
            <br>
            
            <p>Assign papers that have been reviewed and accepted to this session: </p>';

            //query selects from the database all the papers in the conference that have a total rating (acceptance+final)
            //of more than 5, and have the session id set to null which means that they havent been assigned to a session yet
            $result = mysql_query("SELECT paper_id, paper_title FROM paper WHERE (acceptance+final_rating) >= 5 AND session_id is Null
                AND conference_id = $confID") or die(mysql_error());

            //as long as there are entries in the database, they will be retrieved in an array
            while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                // the checkbox list will be populated, getting as a value the paper id
                //and it will display the title of a paper
                echo "<input type=\"checkbox\" name=\"papers[]\" value=\"{$row['paper_id']}\"> {$row['paper_title']}</input><br>";
            }

            //creates a button that submits form information

            echo '</br></br><input type ="submit" name="assign" value="Create"></input></br>';

            if (isset($_POST['assign'])) {
                //an array is created to store all the values of the checkboxes that were clicked
               
                if (!isset($_POST['papers'])) {
                    echo '<script type="text/javascript">alert("Please assign at least one paper to this session");</script>';
                } else {
                    

                    $aPaper = $_POST['papers'];
                    //a variable is initialized to store the length of the array as an integer
                    $n = count($aPaper);
                    // the query inserts the session information into the database creating a new record for the session
                    mysql_query("INSERT INTO session (conference_id, creator_id)
                        VALUES ('$confID', '$crID')") or die(mysql_error());
                    // the mysql insertid method retrieves the identity value of the last record entered in the database
                    $sessID = mysql_insert_id();
                    //loops on all the values in the array
                    for ($i = 0; $i < $n; $i++) {
                        //retrieves the value in the array at position i and stores it in a variable
                        $paperid = $aPaper[$i];
                        //executes a query to update the paper record in the table with the id of the
                        //session it was assigned to
                        mysql_query("UPDATE paper SET session_id = '$sessID' WHERE paper_id = '$paperid'") or die(mysql_error());
                    }
                    
                }
            }

            //checks that the button was clicked
            //closes connection
            mysql_close($con);
            ?>


        </form>
    </body>
</html>